package com.xand.mtgox.connector;

import java.io.IOException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xand.bt.api.MarketApiConst;
import com.xand.bt.api.MarketImageChangeNotify;
import com.xand.bt.util.HttpHelper;

public class MtGoxSynchronizer {

	private static final String FULL_DEPTH_URL = "https://mtgox.com/api/1/BTCUSD/fulldepth";
	
	private static final Logger logger = LoggerFactory.getLogger(MtGoxSynchronizer.class);
	
	public void loadFullMarketDepth() throws IOException, JSONException {
		
		logger.info("Getting initial market depth...");
		
		String jsonMarketImageData = HttpHelper.downloadWebPage(FULL_DEPTH_URL);
		
		JSONObject json = new JSONObject(jsonMarketImageData);
		
		JSONObject returnObject = json.getJSONObject("return");
		JSONArray asks = returnObject.getJSONArray("asks");
		JSONArray bids = returnObject.getJSONArray("bids");
		
		MtGoxMarketChangesStore store = MtGoxMarketChangesStore.getInstance();
		
		for(int i = 0; i < asks.length(); i++) {
			
			JSONObject ask = asks.getJSONObject(i);
			
			long timestamp = ask.getLong("stamp");
			long price_int = ask.getLong("price_int");
			long amount_int = ask.getLong("amount_int");
			
			MarketImageChangeNotify change = new MarketImageChangeNotify();
			change.setDirection(MarketApiConst.DIRECTION_ASK);
			change.setMarketLabel("MTGOX");
			change.setPrice(price_int);
			change.setTime(timestamp / 1000L);
			change.setVolume(amount_int);
			
			store.addMarketChangeNotify(change, true, false);
		}
		
		for(int i = 0; i < bids.length(); i++) {
			
			JSONObject bid = bids.getJSONObject(i);
			
			long timestamp = bid.getLong("stamp");
			long price_int = bid.getLong("price_int");
			long amount_int = bid.getLong("amount_int");
			
			MarketImageChangeNotify change = new MarketImageChangeNotify();
			change.setDirection(MarketApiConst.DIRECTION_BID);
			change.setMarketLabel("MTGOX");
			change.setPrice(price_int);
			change.setTime(timestamp / 1000L);
			change.setVolume(amount_int);
			
			store.addMarketChangeNotify(change, true, false);
		}
		
		logger.info("Initial market depth loaded.");
	}
	
	public void processPendingMessages(TemporaryMarketImageChangesStore tmpStore) {
		
		logger.info("Processing pending messages...");
		
		MtGoxMarketChangesStore store = MtGoxMarketChangesStore.getInstance();
		
		List<MarketImageChangeNotify> changes = tmpStore.getChanges();
		
		logger.info(changes.size() + " messages to go");
		
		for(MarketImageChangeNotify singleChange : changes) {
		
			store.addMarketChangeNotify(singleChange, true, true);
			
		}
		
		logger.info("Pending messages process done.");
		
	}
	
}
